import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import {
    login as apiLogin,
    register as apiRegister,
    getCurrentUser,
    getUserPoints,
    logout as apiLogout,
    refreshToken as apiRefreshToken
} from '@/api/modules/user'
import type { User, LoginRequest, RegisterRequest } from '@/types'

export const useUserStore = defineStore('user', {
    state: () => ({
        // 用户状态
        isLoggedIn: false,
        user: null as User | null,
        token: '',
        refreshToken: '',
        points: 0,

        // 加载状态
        loading: false,
    }),

    getters: {
        // 是否已认证
        isAuthenticated: (state) => state.isLoggedIn,

        // 用户信息
        userInfo: (state) => state.user,

        // 用户名
        username: (state) => state.user?.username || '',

        // 用户ID
        userId: (state) => state.user?.id || 0,

        // 是否是管理员
        isAdmin: (state) => state.user?.role?.toLowerCase() === 'admin',
    },

    actions: {
        // 设置token
        setToken(accessToken: string, refreshToken: string) {
            this.token = accessToken
            this.refreshToken = refreshToken
            this.isLoggedIn = true

            // 保存到localStorage
            localStorage.setItem('accessToken', accessToken)
            localStorage.setItem('refreshToken', refreshToken)
        },

        // 设置用户信息
        setUser(user: User) {
            this.user = user
        },

        // 设置积分
        setPoints(points: number) {
            this.points = points
        },

        // 用户登录
        async login(credentials: LoginRequest) {
            try {
                this.loading = true

                const response = await apiLogin(credentials)

                // 保存token
                this.setToken(response.accessToken, response.refreshToken)

                // 登录成功后，使用token获取当前用户信息
                const userInfo = await getCurrentUser()
                this.setUser(userInfo)
                console.log("user_role:" + userInfo.role)

                // 获取用户积分
                const points = await getUserPoints()
                this.setPoints(points)

                ElMessage.success('登录成功！')
                return true
            } catch (error) {
                console.error('登录失败:', error)
                ElMessage.error('登录失败，请检查用户名和密码')
                return false
            } finally {
                this.loading = false
            }
        },

        // 用户注册
        async register(userData: RegisterRequest) {
            try {
                this.loading = true

                await apiRegister(userData)
                ElMessage.success('注册成功！请登录')
                return true
            } catch (error) {
                console.error('注册失败:', error)
                ElMessage.error('注册失败，请重试')
                return false
            } finally {
                this.loading = false
            }
        },

        // 用户登出
        async logout() {
            try {
                if (this.refreshToken) {
                    await apiLogout(this.refreshToken)
                }
            } catch (error) {
                console.error('登出时发生错误:', error)
            } finally {
                // 清除本地状态
                this.isLoggedIn = false
                this.user = null
                this.token = '',
                this.refreshToken = '',
                this.points = 0

                // 清除localStorage
                localStorage.removeItem('accessToken')
                localStorage.removeItem('refreshToken')

                ElMessage.success('已退出登录')
            }
        },

        // 刷新token
        async refreshAuthToken() {
            try {
                if (!this.refreshToken) {
                    throw new Error('No refresh token')
                }

                const response = await apiRefreshToken(this.refreshToken)
                this.setToken(response.accessToken, response.refreshToken)
                return true
            } catch (error) {
                // 刷新失败，清除登录状态
                this.logout()
                return false
            }
        },

        // 初始化用户状态（从localStorage恢复）
        async initUserState() {
            const accessToken = localStorage.getItem('accessToken')
            const refreshToken = localStorage.getItem('refreshToken')

            if (accessToken && refreshToken) {
                this.token = accessToken
                this.refreshToken = refreshToken
                this.isLoggedIn = true

                try {
                    // 获取用户信息
                    const userInfo = await getCurrentUser()
                    this.setUser(userInfo)

                    // 获取用户积分
                    const points = await getUserPoints()
                    this.setPoints(points)
                } catch (error) {
                    // 如果获取用户信息失败，清除登录状态
                    this.logout()
                }
            }
        },

        // 更新用户信息
        async updateUserInfo(data: Partial<User>) {
            try {
                this.loading = true

                // 这里应该调用更新用户信息的API
                // await updateUserInfo(data)

                // 更新本地状态
                if (this.user) {
                    this.user = { ...this.user, ...data }
                }

                ElMessage.success('用户信息更新成功')
                return true
            } catch (error) {
                console.error('更新用户信息失败:', error)
                ElMessage.error('更新用户信息失败')
                return false
            } finally {
                this.loading = false
            }
        },
    },
})
